﻿using System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;

using VSM.Admin.DAO;

namespace VSM
{
    public partial class SystemGroupEdit : System.Web.UI.Page
    {
        private static DataSet mdsUsers;
        private static DataSet mdsUsersGroup;
        private static DataSet mdsGroups;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["id"] != null && Request.QueryString["id"].Length > 0)
                {
                    btnUpdate.Text = "Update";
                    LoadData(Request.QueryString["id"].ToString());
                    ddl_Dealer.Enabled = false;
                    txtGroupCode.ReadOnly = true;
                    
                    ddl_Dealer.BackColor =
                    txtGroupCode.BackColor = ColorTranslator.FromHtml("#E6E6E6");
                    LoadUserGroup(Request.QueryString["id"].ToString(), "");
                }
                else
                {
                    
                    btnUpdate.Text = "Add";
                    LoadData("");
                    LoadUserGroup("", "");
                }
                LoadUsers("");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void LoadDealer(string aIDDealer)
        {
            DataSet dsDealer = null;
            try
            {
                if (string.IsNullOrEmpty(aIDDealer))
                    dsDealer = SqlHelper.ExecuteDataSet(Data.ConnectionString, CommandType.Text, "Select ID_Dealer, DealerName From tbl_Dealer ");
                else
                    dsDealer = SqlHelper.ExecuteDataSet(Data.ConnectionString, CommandType.Text, "Select ID_Dealer, DealerName From tbl_Dealer Where ID_Dealer = '" + aIDDealer + "'");

                ddl_Dealer.DataSource = dsDealer.Tables[0];
                ddl_Dealer.DataValueField = "ID_Dealer";
                ddl_Dealer.DataTextField = "DealerName";
                ddl_Dealer.DataBind();
                ddl_Dealer.Items.Insert(0,"");

                ddl_Dealer.Items.FindByValue(aIDDealer).Selected = true;
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "LoadDealr", alert, true);
            }
        }

        private void LoadUserGroup(string ID_Group, string ID_Dealer)
        {
            try
            {
                if (string.IsNullOrEmpty(ID_Dealer))
                    mdsUsersGroup = SqlHelper.ExecuteDataSet(Data.ConnectionString, CommandType.Text, "Select ID_User, ID_Group From tbl_UsersGroups Where ID_Group = '" + ID_Group + "'");
                else
                    mdsUsersGroup = SqlHelper.ExecuteDataSet(Data.ConnectionString, CommandType.Text, "Select ID_User, ID_Group From tbl_UsersGroups Where ID_Group = '" + ID_Group + "' and ID_Dealer = '" + ID_Dealer + "'");

                lstBelongUsersGroups.DataSource = mdsUsersGroup.Tables[0];
                lstBelongUsersGroups.DataTextField = "ID_User";
                lstBelongUsersGroups.DataValueField = "ID_User";
                lstBelongUsersGroups.DataBind();
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "LoadUserGroup", alert, true);            
            }
        }

        private void LoadUsers(string ID_Dealer)
        {
            try
            {
                if (string.IsNullOrEmpty(ID_Dealer))
                    mdsUsers = SqlHelper.ExecuteDataSet(Data.ConnectionString, CommandType.Text, "Select ID_User From tbl_MasterUsers ");
                else
                    mdsUsers = SqlHelper.ExecuteDataSet(Data.ConnectionString, CommandType.Text, "Select ID_User From tbl_MasterUsers Where ID_Dealer = '" + ID_Dealer + "'");
                lstAvailableUsers.DataSource = mdsUsers.Tables[0];
                lstAvailableUsers.DataTextField = "ID_User";
                lstAvailableUsers.DataValueField = "ID_User";
                lstAvailableUsers.DataBind();
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "LoadUsers", alert, true);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void LoadData(string aID)
        {
            if (!string.IsNullOrEmpty(aID))
            {
                mdsGroups = SqlHelper.ExecuteDataSet(Data.ConnectionString, CommandType.Text, "Select * From tbl_Groups Where ID_Group = '" + aID + "'");
                BindData(mdsGroups.Tables[0]);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            DataRow dr = tblData.Rows[0];
            txtGroupCode.Text = dr["ID_Group"].ToString();
            txtGroupName.Text = dr["Description"].ToString();
            LoadDealer(dr["ID_Dealer"].ToString());
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            /*try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    DateTime poDate = Convert.ToDateTime(this.txtPODate.Text.Trim());
                    DataTable tblIPO = (DataTable)ViewState["POTable"];
                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectVendor":
                            this.lblError.Visible = false;
                            this.txtVendorCode.Text = Session["ChosenVendorCode"] != null ? Session["ChosenVendorCode"].ToString() : "";
                            this.txtVendorName.Text = Session["ChosenVendorName"] != null ? Session["ChosenVendorName"].ToString() : "";
                            tblIPO.Rows.Clear();
                            Session["ChosenItem"] = null;
                            tblIPO = LoadSetupItem(poDate, tblIPO);
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }*/
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                ArrayList sqlList = new ArrayList();
                DatabaseParameters KeyParameters = new DatabaseParameters();
                DatabaseParameters ValueParameters = new DatabaseParameters();

                if (Request.QueryString["id"] != null && Request.QueryString["id"].Length > 0) // Update Group
                {
                    KeyParameters.Add(new DatabaseParameter("ID_Group", txtGroupCode.Text));
                    ValueParameters.Add(new DatabaseParameter("Description", txtGroupName.Text.Trim(), true));
                    ValueParameters.Add(new DatabaseParameter("UpdatedUser", "Admin")); // hard code to test.
                    ValueParameters.Add(new DatabaseParameter("UpdatedTime", DateTime.Now.ToString("MM/dd/yyyy")));
                    SqlHelper.UpdateCommand(KeyParameters, ValueParameters, "tbl_Groups");
                }
                else // Add Group
                {
                    ValueParameters.Add(new DatabaseParameter("ID_Group", txtGroupCode.Text));
                    ValueParameters.Add(new DatabaseParameter("Description", txtGroupName.Text.Trim(), true));
                    ValueParameters.Add(new DatabaseParameter("CreatedUser", "Admin")); // hard code to test.
                    ValueParameters.Add(new DatabaseParameter("CreatedTime", DateTime.Now.ToString("MM/dd/yyyy")));

                    SqlHelper.InsertCommand(ValueParameters, "tbl_Groups");
                }

                sqlList.Add(SqlHelper.SQL);

                // update user-group
                foreach (DataRow dr in mdsUsersGroup.Tables[0].Rows)
                {
                    KeyParameters.Clear();
                    ValueParameters.Clear();

                    switch(dr.RowState)
                    {
                        case DataRowState.Deleted:
                            KeyParameters.Add(new DatabaseParameter("ID_Group", txtGroupCode.Text));
                            KeyParameters.Add(new DatabaseParameter("ID_User", dr["ID_User", DataRowVersion.Original].ToString()));
                            SqlHelper.DeleteCommand(KeyParameters, "tbl_UsersGroups");
                            sqlList.Add(SqlHelper.SQL);
                            break;

                        case DataRowState.Added:
                            ValueParameters.Add(new DatabaseParameter("ID_Group", txtGroupCode.Text));
                            ValueParameters.Add(new DatabaseParameter("ID_User", dr["ID_User"].ToString()));
                            ValueParameters.Add(new DatabaseParameter("CreatedUser","Admin")); // Hard code for test
                            ValueParameters.Add(new DatabaseParameter("CreatedTime", DateTime.Now.ToString("MM/dd/yyyy")));
                            SqlHelper.InsertCommand(ValueParameters, "tbl_UsersGroups");
                            sqlList.Add(SqlHelper.SQL);
                            break;
                    }                
                }

                if (!SqlHelper.ExecuteQuery(sqlList, Data.ConnectionString))
                {
                    string alert = "alert('Error: " + SqlHelper.ErrMsg + " ');";
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "btnUpdate_Click", alert, true);
                }
                else
                {
                    this.lblError.Text = "Operation complete successful!";
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
            }
            this.lblError.Visible = true;
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                if (lstAvailableUsers.SelectedIndex < 0) return;

                DataRow ldrUser = mdsUsers.Tables[0].Rows[lstAvailableUsers.SelectedIndex];
                DataRow ldrUsersGroups;
                // If the Group is existing in the List --> do nothing
                for (int li_index = 0; li_index < mdsUsersGroup.Tables[0].Rows.Count; li_index++)
                {
                    ldrUsersGroups = mdsUsersGroup.Tables[0].Rows[li_index];
                    if (ldrUser["ID_User"].ToString() == ldrUsersGroups["ID_User"].ToString()) return;
                }

                // The Group is not existing in the List --> add the Group to the List/UsersGroupsSet
                ldrUsersGroups = mdsUsersGroup.Tables[0].NewRow();
                ldrUsersGroups["ID_User"] = ldrUser["ID_User"];
                ldrUsersGroups["ID_Group"] = txtGroupCode.Text.Trim();
                mdsUsersGroup.Tables[0].Rows.Add(ldrUsersGroups);
                lstBelongUsersGroups.DataSource = mdsUsersGroup.Tables[0];
                lstBelongUsersGroups.DataTextField = "ID_User";
                lstBelongUsersGroups.DataValueField = "ID_User";
                lstBelongUsersGroups.DataBind();
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "Add", alert, true);                
            }
        }

        protected void btnRemove_Click(object sender, EventArgs e)
        {
            try
            {
                if (mdsUsersGroup.Tables[0].Rows.Count == 0)
                {
                    btnRemove.Enabled = false;
                    return;
                }

                DataRow ldrUsersGroups = mdsUsersGroup.Tables[0].Rows[lstBelongUsersGroups.SelectedIndex];
                ldrUsersGroups.Delete();
                lstBelongUsersGroups.Items.RemoveAt(lstBelongUsersGroups.SelectedIndex);
                btnAdd.Enabled = true;
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "Remove", alert, true);    
            }
        }
    }
}